package com.zhen.aikan.controller;

import com.zhen.aikan.constant.Constants;
import com.zhen.aikan.entity.Scheduled;
import com.zhen.aikan.service.IScheduledService;
import com.zhen.aikan.util.CronUtils;
import com.zhen.aikan.util.StringUtils;
import com.zhen.aikan.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author LiJiaZhen
 * @date 2023/9/18 18:29
 */
@Api(tags = "定时任务调度控制器")
@RestController
@RequestMapping("/api/scheduled")
public class ScheduledController {
    @Autowired
    private IScheduledService scheduledService;

    /**
     * {
     *   "concurrent": "1",
     *   "cronExpression": "0/10 * * * * ?",
     *   "invokeTarget": "task.getUpdatedVod('https://collect.wolongzy.cc/api.php/provide/vod/?ac=detail&h=24&pg=')",
     *   "jobGroup": "vodGroup",
     *   "jobId": 1,
     *   "jobName": "视频更新任务",
     *   "misfirePolicy": "1",
     *   "remark": "",
     *   "status": "0"
     * }
     * @param job
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "新增task任务", notes = "将任务信息添加到数据库")
    @PostMapping("/add")
    public Result add(@RequestBody Scheduled job) throws Exception {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return Result.fail();
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return Result.fail();
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_LDAP)) {
            return Result.fail();
        }
        scheduledService.insertJob(job);
        return Result.ok();
    }

    /**
     * {
     *   "jobId": 1,
     *   "status": "0"
     * }
     * @param job
     * @return
     * @throws SchedulerException
     */
    @ApiOperation(value = "根据任务ID修改状态，0启动 1暂停")
    @PostMapping("/changeStatus")
    public Result changeStatus(@RequestBody Scheduled job) throws SchedulerException {
        scheduledService.changeStatus(job);
        return Result.ok();
    }

    @ApiOperation(value = "修改task任务", notes = "根据ID修改已有的任务，同时更新调度任务信息")
    @PostMapping( "/update")
    public Result update(@RequestBody Scheduled job) throws Exception {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return Result.fail();
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return Result.fail();
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_LDAP)) {
            return Result.fail();
        }
        scheduledService.updateJob(job);
        return Result.ok();
    }
}
